package com.example.newinfinity

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.example.newinfinity.File.FileManager
import com.example.newinfinity.MyViewModel.UserViewModel
import com.example.newinfinity.UserRoom.User
import com.example.newinfinity.databinding.FragmentLoginBinding
import com.example.newinfinity.databinding.FragmentLottieAnimBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LoginFragment : BaseFragment<FragmentLoginBinding>() {
    private val userViewModel: UserViewModel by activityViewModels()

    //用于保存登录时用户在editText中输入的用户信息
    private var userName = ""
    private var userPassword = ""

    override fun initViewBinding(): FragmentLoginBinding {
        return FragmentLoginBinding.inflate(layoutInflater)
    }

    //在该方法中可编写onCreateView时期需要编写的内容
    override fun initView() {
        super.initView()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //立即注册 跳转到注册界面
        mBinding.registerNow.setOnClickListener {
            findNavController().navigate(R.id.action_loginFragment_to_registerFragment)
        }
        //点击登录按钮 进行登录 跳转到homeFragment绘画界面
        loginToHomeFragment()
    }

    private fun loginToHomeFragment() {
        mBinding.loginButton.setOnClickListener {
            if (mBinding.userName.text?.isEmpty() == true || mBinding.userPassword.text?.isEmpty() == true) {
                Toast.makeText(requireContext(), "请完善登录信息", Toast.LENGTH_SHORT).show()
            }
            if (mBinding.userName.text?.isEmpty() == false && mBinding.userPassword.text?.isEmpty() == false) {
                //在Room中 判断是否注册了这个用户的信息 判断是否跳转主界面 是否修改该用户为登录用户
                loginUser()
            }
        }
    }

    private fun loginUser() {
        userName = mBinding.userName.text.toString()
        userPassword = mBinding.userPassword.text.toString()
        //异步处理 避免主线程阻塞
        lifecycleScope.launch {  //获取当前用户登录时输入的信息判断是否该信息注册过
            val inputUser = userViewModel.getUserByName(userName, userPassword)
            if (inputUser != null) {  //该用户之前注册过
                //更新当前应用登录的用户信息（可空）
                userViewModel.getCurrentLoginInUser()?.let { currentLoginInUser ->
                    currentLoginInUser.isLogin = false
                    userViewModel.updateUser(currentLoginInUser)
                }
                inputUser.isLogin = true  //该用户现在为正在登录用户
                userViewModel.updateUser(inputUser)

                //创建当前登录用户存储图片对应的文件夹
                FileManager.instance.createFilePath(inputUser.userName)

                withContext(Dispatchers.Main){  //主线程toast并跳转主界面
                    Toast.makeText(requireContext(), "登录成功", Toast.LENGTH_SHORT).show()
                    findNavController().navigate(R.id.action_loginFragment_to_homeFragment)
                }
            } else {
                //该用户之前未注册 主线程toast提醒未注册
                withContext(Dispatchers.Main){
                    Toast.makeText(requireContext(), "用户未注册", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

}